package it.cinema.mobile.biz;


import it.cinema.mobile.data.Parameter;
import it.cinema.mobile.data.Film;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.sql.DataSource;

@ManagedBean
@ApplicationScoped
public class FilmDAO {
	private static final Logger log = Logger.getLogger(it.cinema.mobile.data.Film.class.getName());

	@Resource(name=("jdbc/dbcinema"))
	private DataSource ds;
	
	public List<Film> findFilm(Parameter parameter){
		ArrayList<Film> films = null;
		try {

			Connection con = ds.getConnection();
			Statement statement = con.createStatement();
			String query = "select * from film f ";		

			String filmIDs = parameter.getFilms();
			if (filmIDs != null && !filmIDs.isEmpty()){
				StringTokenizer st = new StringTokenizer(filmIDs,",");
				query = query + "where ";
				while (st.hasMoreElements()) {
					String token = st.nextElement().toString();
					query = query + "f.idfilm = '"+token+"'";
					if(st.hasMoreElements())
						query = query + " or ";
				}
			}

			log.info("Query : "+query);
			
			ResultSet resultSet = statement.executeQuery(query);
			films = new ArrayList<Film>();
			Film f = null;
			for (; resultSet.next(); films.add(f))
				f = new Film(resultSet.getString("titolo"),
						resultSet.getString("desc_breve"),
						resultSet.getString("trama"),
						resultSet.getString("locandina"));

			resultSet.close();
			statement.close();
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return films;
	}
}